import { fileURLToPath, URL } from 'node:url'

import { ConfigEnv, loadEnv, UserConfigExport } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import process from 'node:process'
// @ts-ignore
import EslintPlugin from 'vite-plugin-eslint'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv): UserConfigExport => {
  const isProd = mode === 'production'
  const env = loadEnv(mode, process.cwd())

  return {
    plugins: [
      vue(),
      vueJsx(),
      EslintPlugin({
        cache: false,
        include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'] // 检查的文件
      }),
      //自动引入组件
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: false // css in js
          })
        ]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
      extensions: ['.ts', '.tsx', '.js', '.mjs', '.vue', '.json', '.less', '.css']
    },
    esbuild: {
      /** 打包时移除 console.log */
      pure: ['console.log'],
      /** 打包时移除 debugger */
      drop: ['debugger'],
      /** 打包时移除所有注释 */
      legalComments: 'none'
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      assetsInlineLimit: 8192,
      sourcemap: !isProd,
      emptyOutDir: true,
      /** 禁用 gzip 压缩大小报告 */
      reportCompressedSize: true,
      rollupOptions: {
        output: {
          // 静态资源打包区分文件夹
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          manualChunks(id: string) {
            if (id.includes('node_modules')) {
              return (
                id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)?.groups!
                  .moduleName ?? 'vender'
              )
            }
            // if (id.includes('node_modules')) {
            //   console.log(id, 'id')
            //   return id.toString().split('node_modules/')[1].split('/')[1].toString()
            // }
            return ''
          }
        }
      }
    },
    server: {
      open: true,
      host: '0.0.0.0',
      port: 5000
    },
    preview: {
      port: 8888
    }
  }
}
